from subprocess import Popen, PIPE
import time
import os
import random
import threading

MAX_SIM = 100

class Sim:
	PARAMS = [
			#["0", "resources/configuration0/missions0", "resources/configuration0/sergeants0", "resources/configuration0/items0"], 
			#["1", "resources/configuration1/missions1", "resources/configuration1/sergeants1", "resources/configuration1/items1"], 
			["2", "resources/configuration2/missions2", "resources/configuration2/sergeants2", "resources/configuration2/items2"], 
			["3", "resources/configuration3/missions3", "resources/configuration3/sergeants3", "resources/configuration3/items3"] 
		]

	COMMANDS = ["warehouse", "sergeants", "completeMissions", "incompleteMissions"]
	def __init__(self, params):
		t = time.strftime("%s")
		self._stdout = file("Fazz/logs/%s_%s.stdout" % (params[0], t), "wb")
		self._log = "Fazz/logs/%s_%s.log" % (params[0], t)

		self._sim = Popen(["java", "-jar", "sim.jar"] + params[1:] + [self._log,], stdin=PIPE, stdout = self._stdout, stderr = file("/dev/null", "wb"))

		self.alive = True

	def query(self):
		self._stdout.flush()
		self._stdout.write("Query: " + time.strftime("%c") + "\n")
		for cmd in Sim.COMMANDS:
			self._sim.stdin.write("%s\x0a" % cmd)

	def stop(self):
		self._sim.stdin.write("stop now\x0a")
		self._stdout.close()
		self.alive = False

	def join(self):
		self._sim.wait()


sims = []
for p in Sim.PARAMS:
	s = Sim(p)
	sims.append(s)
	time.sleep(0.5)
	s.query()


def stopper():
	while raw_input("Stop?") != "y":
		pass

	for s in sims:
		s.stop()
		s.join()

st = threading.Thread(target=stopper)
st.start()

cont  = True
while cont:
	cont = False
	for s in sims:
		if s.alive:
			cont = True
			try:
				s.query()
				time.sleep(random.randint(1, 10))
			except:
				cont = False


st.join()
